package com.example.im

import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkbasecomponent.http.lib.CallBack
import cc.vv.lkbasecomponent.http.LKHttp
import android.text.TextUtils
import com.example.baselibrary.util.LKToastUtil
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMDirect
import cc.vv.lkimcomponent.lkim.bean.body.LKIMVideoBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.body.LKIMImageBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMStatus
import cc.vv.lkimcomponent.lkim.inter.LKIMStatusInter
import cc.vv.lkimcomponent.lkim.operate.LKIMSend
import cc.vv.lkimcomponent.view.emoji.ParseEmojiOperate
import com.example.BaseNewApplication
import com.example.baselibrary.db.dao.GroupDao
import com.example.baselibrary.db.table.GroupTable
import com.example.util.finallist.IMExtKey
import java.io.File
import java.io.IOException


/**
 * @author  chaohaipeng  on 2018/7/17.
 */
class SKIMSend private constructor(){
    private object mHolder {
        val instance = SKIMSend()
    }
    companion object {
        fun getInstance(): SKIMSend {
            return mHolder.instance
        }
    }

    /**
     * 文本消息发送
     *
     * @param account      帐号
     * @param content      内容
     * @param lkimChatType 单聊群聊    LKIMChatType
     */
    fun sendTxt(account: String, content: String, lkimChatType: LKIMChatType) {
        var content = content
        if (!isEmpty(account, content, lkimChatType)) {
        //  var mcontent=  EmojiconUtils.getSmiledText(SKApplication.getInstance(), content)
            content = ParseEmojiOperate.getInstance().emoji2Unicode(content)
//            val spannableString = ParseEmojiOperate.getInstance().parseEmoji(content, 20)
            val lkimMessage = IMMessageInit.getInstance().initTxt(account, content, lkimChatType)
            sendOperate(lkimMessage, lkimChatType)
        }
    }

    /**
     * 发送群组@成员功能
     *
     * @param account        帐号
     * @param content        内容
     * @param atMembersIdStr 被@的成员id，之间使用英文逗号隔开
     */
    fun sendGroupAtMemberTxt(account: String, content: String, atMembersIdStr: String) {
        if (!isEmpty(account, content)) {
            val lkimMessage = IMMessageInit.getInstance().initTxt(account, content, LKIMChatType.GroupChat)
            lkimMessage.setAttribute(IMExtKey.EXTKEY_ATMEMBERSIDSTR, atMembersIdStr)
            sendOperate(lkimMessage, LKIMChatType.GroupChat)
        }
    }


    /**
     * 语音消息发送
     *
     * @param account      帐号
     * @param filePath     文件路径
     * @param duration     时间(秒)
     * @param lkimChatType 单聊群聊    LKIMChatType
     */
    fun sendVoice(account: String, filePath: String, duration: Int, lkimChatType: LKIMChatType) {
        if (!isEmpty(account, filePath, lkimChatType)) {
            val lkimMessage = IMMessageInit.getInstance().initVoice(account, filePath, duration, lkimChatType)
            sendOperate(lkimMessage, lkimChatType)
        }
    }

    /**
     * 图片类型消息发送
     *
     * @param account      帐号
     * @param imagePath    图片路径(本地路径)
     * @param lkimChatType 单聊群聊    LKIMChatType
     */
    fun sendImage(account: String, imagePath: String?, lkimChatType: LKIMChatType) {
        if (!isEmpty(account, imagePath, lkimChatType)) {
            if(imagePath!=null){
                val lkimMessage = IMMessageInit.getInstance().initImage(account, imagePath, lkimChatType)
                sendOperate(lkimMessage, lkimChatType)
            }
        }
    }


    /**
     * 自定义表情发送
     *
     * @param account      帐号
     * @param imageUrl     表情url(网络路径)
     * @param width        宽
     * @param height       高
     * @param lkimChatType 单聊群聊
     */
    fun sendCustomPhiz(account: String, imageUrl: String, width: String, height: String, lkimChatType: LKIMChatType) {
        if (!isEmpty(account, imageUrl, width, height, lkimChatType)) {
            val lkimMessage = IMMessageInit.getInstance().initCustomPhiz(account, imageUrl, width, height, lkimChatType)
            sendOperate(lkimMessage, lkimChatType)
        }
    }

    /**
     * 发送段视频
     *
     * @param account      帐号
     * @param videoUrl     视频路径
     * @param thumbUrl     视频缩略图片地址
     * @param duration     时间(秒)
     * @param lkimChatType 单聊群聊    LKIMChatType
     */
    fun sendVideo(account: String, videoUrl: String, thumbUrl: String, duration: Int, lkimChatType: LKIMChatType) {
        if (!isEmpty(account, videoUrl, thumbUrl, lkimChatType)) {
            val lkimMessage = IMMessageInit.getInstance().initVideo(account, videoUrl, thumbUrl, duration, lkimChatType)
            sendOperate(lkimMessage, lkimChatType)
        }
    }


    /**
     * 基本消息发送处理
     *
     * @param lkimMessage  消息体
     * @param lkimChatType 单聊群聊   LKIMChatType
     */
    private fun sendOperate(lkimMessage: LKIMMessage, lkimChatType: LKIMChatType) {
        lkimMessage.lkimChatType = lkimChatType
        //IM发消息异常时打开注释掉下面的方法
//        if (null != lkimMessage.getEMMessage() ) {
//            lkimMessage.getEMMessage().setMessageStatusCallback(object : EMCallBack {
//                override fun onSuccess() {
//                }
//
//                override fun onError(code: Int, error: String) {
//                    LogOperate.e("消息失败===" + error)
//                }
//
//                override fun onProgress(progress: Int, status: String) {
//                }
//            })
//            EMClient.getInstance().chatManager().sendMessage(lkimMessage.emMessage)
//    }

      LKIMSend.getInstance().sendMessage(lkimMessage, lkimChatType, object : LKIMStatusInter {
          override fun start(lkimMessage: LKIMMessage) {
              /**
               * 插入消息到聊天界面
               */
              IMReceiveService.getInstance().sendInsertCache(lkimMessage.toAccount, lkimMessage, true)
          }

          override fun onSuccess(oldMessageId: String, lkimMessage: LKIMMessage) {
              IMReceiveService.getInstance().sendRefreshMessage(lkimMessage.toAccount, oldMessageId, lkimMessage)
          }

          override fun onProgress(i: Int, s: String) {

          }

          override fun onError(oldMessageId: String, lkimMessage: LKIMMessage) {
              IMReceiveService.getInstance().sendRefreshMessage(lkimMessage.toAccount, oldMessageId, lkimMessage)
          }
      })
    }



    /**
     * 消息撤销
     *
     * @param account      帐号
     * @param messageId    消息id
     * @param lkimChatType 单聊群聊   LKIMChatType
     */
    fun cmdRepeal(account: String, messageId: String, lkimChatType: LKIMChatType, cmdSendInter: CmdSendInter) {
        if (!isEmpty(account, messageId, lkimChatType, cmdSendInter)) {
            val lkimMessage = IMMessageInit.getInstance().initCMDRepeal(account, messageId, lkimChatType)
            sendCmdOperate(lkimMessage, lkimChatType, cmdSendInter)
        }
    }




    /**
     * 消息已读透传
     *
     * @param account        帐号
     * @param outLKIMMessage 消息体
     * @param lkimChatType   单聊群聊   LKIMChatType
     */
    fun cmdAckRead(account: String, outLKIMMessage: LKIMMessage, lkimChatType: LKIMChatType, cmdSendInter: CmdSendInter) {
        if (!isEmpty(account, outLKIMMessage, lkimChatType, cmdSendInter)) {
            val ackLKIMMessage = IMMessageInit.getInstance().initCMDAck(account, outLKIMMessage.msgId, lkimChatType)
            sendCmdOperate(ackLKIMMessage, lkimChatType, cmdSendInter)
        }
    }

    /**
     * 群组变动通知透传
     *
     * @param groupId     群组id
     * @param groupNick   群组昵称
     * @param groupAvatar 群组头像
     * @param inform      通知内容
     * @param toUserIds   目标用户id
     */
    fun cmdGroupChange(groupId: String, groupNick: String, groupAvatar: String, inform: String, cmdSendInter: CmdSendInter,  toUserIds: String) {
        if (!isEmpty(groupId, cmdSendInter)) {
            val groupTable = GroupTable(groupId, groupNick, groupAvatar)
            GroupDao.getInstance().updateGroup(groupTable)
            val lkimMessage = IMMessageInit.getInstance().initCMDGroupChange(groupId, groupNick, groupAvatar, inform, toUserIds)
            sendCmdOperate(lkimMessage, LKIMChatType.GroupChat, cmdSendInter)
        }
    }



    /**
     * CMD类型消息发送处理
     *
     * @param cmdLKIMMessage 消息体
     * @param lkimChatType   单聊群聊   LKIMChatType
     */
    private fun sendCmdOperate(cmdLKIMMessage: LKIMMessage, lkimChatType: LKIMChatType, cmdSendInter: CmdSendInter) {
        LKIMSend.getInstance().sendMessage(cmdLKIMMessage, lkimChatType, object : LKIMStatusInter {
            override fun start(lkimMessage: LKIMMessage) {

            }

            override fun onSuccess(s: String, lkimMessage: LKIMMessage) {
                cmdSendInter.onSuccess(lkimMessage)
            }

            override fun onProgress(i: Int, s: String) {

            }

            override fun onError(s: String, lkimMessage: LKIMMessage) {
                cmdSendInter.faile(lkimMessage)
            }
        })
    }


    /**
     * 普通消息重发
     *
     * @param lkimMessage 消息体
     */
    fun reSendOperate(lkimMessage: LKIMMessage) {
        if (LKIMChatType.GroupChat == lkimMessage.lkimChatType) {
            IMMessageInit.getInstance().initGroupInfoExt(lkimMessage.toAccount, lkimMessage)
        }
        LKIMSend.getInstance().sendMessage(lkimMessage, lkimMessage.lkimChatType, object : LKIMStatusInter {
            override fun start(lkimMessage: LKIMMessage) {
                lkimMessage.setLKIMStatus(LKIMStatus.INPROGRESS)
                IMReceiveService.getInstance().sendRefreshMessage(lkimMessage.toAccount, lkimMessage.msgId, lkimMessage)
            }

            override fun onSuccess(oldMessageId: String, lkimMessage: LKIMMessage) {
                IMReceiveService.getInstance().sendRefreshMessage(lkimMessage.toAccount, oldMessageId, lkimMessage)
            }

            override fun onProgress(i: Int, s: String) {

            }

            override fun onError(oldMessageId: String, lkimMessage: LKIMMessage) {
                IMReceiveService.getInstance().sendRefreshMessage(lkimMessage.toAccount, oldMessageId, lkimMessage)

            }
        })
    }









    /**
     * 图片转发
     *
     * @param account      帐号
     * @param lkimChatType 发送到单聊群聊 LKIMChatType
     * @param lkimDirect   消息自身为发送方还是接收方
     * @param lkimBody     图片消息体
     */
    private fun forwardeImage(account: String, lkimChatType: LKIMChatType, lkimDirect: LKIMDirect, lkimBody: LKIMImageBody) {
        if (LKIMDirect.SEND == lkimDirect) {
            sendImage(account, lkimBody.localUrl, lkimChatType)
        } else {
            val imageFile = getFile("image", "forwardeImage.jpg")
            if (isEmpty(imageFile)) {
                LKToastUtil.showToastShort("转发失败")
            } else {

                downLoadFile(lkimBody.remoteUrl, imageFile?.getAbsolutePath(), object : SendDownInter {
                    override fun success(filePath: String?) {
                        sendImage(account, filePath, lkimChatType)
                    }

                    override fun failure() {
                        LKToastUtil.showToastShort("转发失败")
                    }
                })
            }
        }
    }

    /**
     * 转发小视频
     *
     * @param account       帐号
     * @param lkimChatType  发送到单聊群聊 LKIMChatType
     * @param lkimDirect    消息自身为发送方还是接收方
     * @param lkimBody      视频消息体
     * @param videoLocalUrl 视频文件本地路径
     */
    private fun forwardeVideo(account: String, lkimChatType: LKIMChatType, lkimDirect: LKIMDirect, lkimBody: LKIMVideoBody, videoLocalUrl: String) {
        if (LKIMDirect.SEND == lkimDirect) {
            sendVideo(account, lkimBody.localUrl, lkimBody.localThumbUrl, lkimBody.duration, lkimChatType)
        } else {
            val imageFile = getFile("video", "forwardeVideo.mp4")
            if (isEmpty(imageFile)) {
                LKToastUtil.showToastShort("转发失败")
            } else {
                if (TextUtils.isEmpty(videoLocalUrl)) {
                    downLoadFile(lkimBody.remoteUrl, imageFile?.getAbsolutePath(), object : SendDownInter {
                        override fun success(filePath: String?) {
                            forwardeVideo(account, lkimChatType, lkimDirect, lkimBody, filePath!!)
                        }

                        override fun failure() {
                            LKToastUtil.showToastShort("转发失败")
                        }
                    })
                } else {
                    downLoadFile(lkimBody.remoteThumbUrl, imageFile!!.getAbsolutePath(), object : SendDownInter {
                        override fun success(filePath: String?) {
                            sendVideo(account, videoLocalUrl, filePath!!, lkimBody.duration, lkimChatType)
                        }

                        override fun failure() {
                            LKToastUtil.showToastShort("转发失败")
                        }
                    })
                }
            }
        }
    }

    /**
     * 创建文件
     *
     * @param dirName  文件夹名称
     * @param fileName 文件名称
     * @return 文件
     */
    private fun getFile(dirName: String, fileName: String): File? {
        var file: File? = null
        if (!isEmpty(dirName, fileName)) {
            val fileDir = BaseNewApplication.getInstance()?.getExternalFilesDir(dirName)
            file = File(fileDir, System.currentTimeMillis().toString() + fileName)
            if (!file!!.exists()) {
                try {
                    file!!.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return file
    }


    /**
     * 非空判断
     *
     * @param params 需要判断的参数
     * @return 是否包含空数据
     */
    private fun isEmpty(vararg params: Any?): Boolean {
        var isEmpty = false
        if (null != params) {
            for (param in params) {
                if (param is String) {
                    if (TextUtils.isEmpty(param)) {
                        isEmpty = true
                        break
                    }
                } else {
                    if (null == param) {
                        isEmpty = true
                        break
                    }
                }
            }
        }
        return isEmpty
    }

    /**
     * 文件下载
     *
     * @param url      url
     * @param filePath 保存地址
     * @param inter    操作回调
     */
    private fun downLoadFile(url: String, filePath: String?, inter: SendDownInter) {
        LKHttp.downLoadWithGet(url, null, filePath, true, object : CallBack<String>() {
            override fun onDownLoadProgress(url: String?, filePath: String?, progress: Int) {
                super.onDownLoadProgress(url, filePath, progress)
            }

            override fun onDownLoadFailure(url: String?, filePath: String?) {
                super.onDownLoadFailure(url, filePath)
                inter.failure()
            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                inter.failure()
            }

            override fun onDownLoadSuccess(url: String?, filePath: String?) {
                super.onDownLoadSuccess(url, filePath)
                inter.success(filePath)
            }
        }, false)

    }


    /**
     * 发送相关下载回调
     */
    private interface SendDownInter {
        fun success(filePath: String?)

        fun failure()
    }


    /**
     * 透传类型消息
     */
    interface CmdSendInter {
        fun onSuccess(lkimMessage: LKIMMessage)

        fun faile(lkimMessage: LKIMMessage)
    }

}